# -*- coding: utf-8 -*-
# flake8: noqa

from qiniu import Auth, put_data, etag, urlsafe_base64_encode
import qiniu.config

# 需要填写你的 Access Key 和 Secret Key
access_key = 'V_xlJjJOVoTYzXpuY0dKH1s1SF2m5ITXzIqcxwib'
secret_key = 'HuNmaIzEabXHBV97VO6Gcmo9ZuQLFW93_yKLxh0a'

# 要上传的空间
bucket_name = 'flaskprojects'


def stroage_image(data):
    '''用户将图片上传到七牛用的'''

    if not data:
        return None

    # 构建鉴权对象
    q = Auth(access_key, secret_key)

    # #上传到七牛后保存的文件名
    # key = 'my-python-logo.png';

    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name)  # , key, 3600

    # 要上传文件的本地路径
    # localfile = './sync/bbb.jpg'

    ret, info = put_data(token, None, data)  # key, localfile
    print(ret.get('key'))
    # assert ret['key'] == key
    # assert ret['hash'] == etag(localfile)

    if info.status_code != 200:
        raise Exception('七牛上传文件失败')

    return ret.get('key')


if __name__ == '__main__':
    file_name = raw_input('输入文件名:')
    with open(file_name, 'rb') as f:
        stroage_image(f.read())
